package com.sinovatech.ologger.actionlog.converters;

import java.io.File;
import java.util.Date;
import java.util.UUID;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.sinovatech.ologger.constants.Globals;
import com.sinovatech.ologger.core.util.BeanUtils;
import com.sinovatech.ologger.core.util.FileManager;
import com.sinovatech.ologger.util.DateUtil;
import com.sinovatech.ologger.util.LogUtil;
import com.opensymphony.xwork.ActionSupport;

/**
 * 文件上传转换器, 针对webwork/struts2
 * LogHelper.registerLogConverter(new UploadFileConverter(), "uploadFile");//文件上传转换器 
 * @author nanquan
 *
 */
public class UploadFileConverter implements LogConverter {

	private static final Log logger = LogFactory.getLog(LogConverterHelper.class);
	
	public static final String IMPORT_DIRECTORY = "importfile" + File.separator;

	public static final String SEPARATED_COMMA = ",";
	
	public String convert(Object obj) {
		if (obj instanceof ActionSupport) {
			StringBuilder filePath = new StringBuilder(Globals.ATTRIBUTE_UPLOAD_PATH_WEB);
			String uploadFileName = null;
			String locationFile = null;
			try {
				File file = (File) BeanUtils.forceGetProperty(obj, "file");
				uploadFileName = (String) BeanUtils.forceGetProperty(obj, "uploadFileName");
				String month = DateUtil.dateToString(new Date(), "yyyyMM");
				String destFileName = IMPORT_DIRECTORY + month + File.separator + UUID.randomUUID() + File.separator + "uploadFile"
						+ uploadFileName.substring(uploadFileName.lastIndexOf("."), uploadFileName.length());
				locationFile = FileManager.saveFile(file, destFileName);
				logger.info(locationFile);
				filePath.append(destFileName);
			} catch (Exception e) {
				logger.equals(LogUtil.stackTraceToString(e));
			}
			return "[" + uploadFileName + SEPARATED_COMMA + filePath.toString().replace(File.separator, "/") + SEPARATED_COMMA + locationFile + "]";
		}
		return "";
	}
}